package com.shuorikeji.huohuo.ui.me;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.shuorikeji.huohuo.BuildConfig;
import com.shuorikeji.huohuo.R;
import com.shuorikeji.huohuo.app.AppManager;
import com.shuorikeji.huohuo.base.BasePresenterActivity;
import com.shuorikeji.huohuo.bean.VersionInfoBean;
import com.shuorikeji.huohuo.bean.VersionMainBean;
import com.shuorikeji.huohuo.callback.ClickCallBack;
import com.shuorikeji.huohuo.common.Constant;
import com.shuorikeji.huohuo.http.ApiUrl;
import com.shuorikeji.huohuo.mvp.AllPresenter;
import com.shuorikeji.huohuo.ui.LoginActivity;
import com.shuorikeji.huohuo.ui.WebViewActivity;
import com.shuorikeji.huohuo.utils.BusinessUtils;
import com.shuorikeji.huohuo.utils.PreUtils;
import com.shuorikeji.huohuo.utils.ToastShowUtil;
import com.luck.picture.lib.permissions.RxPermissions;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class SetActivity extends BasePresenterActivity<AllPresenter> {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.rl_clear_cache)
    RelativeLayout rlClearCache;
    @BindView(R.id.rl_user_xy)
    RelativeLayout rlUserXy;
    @BindView(R.id.rl_ys_xy)
    RelativeLayout rlYsXy;
    @BindView(R.id.rl_about_us)
    RelativeLayout rlAboutUs;
    @BindView(R.id.rl_zx_zh)
    RelativeLayout rlZxZh;
    @BindView(R.id.tv_tc_login)
    TextView tvCtLogin;
    @BindView(R.id.tv_cache)
    TextView tvCache;
    @BindView(R.id.rl_version)
    RelativeLayout rlVersion;
    @BindView(R.id.ll_new_version)
    LinearLayout llNewVersion;
    @BindView(R.id.tv_version_info)
    TextView tvVersionInfo;
    @BindView(R.id.sb_xz_jd)
    SeekBar sbXzJd;
    @BindView(R.id.tv_xz_apk)
    TextView tvXzApk;

    private String apkXzPath;
    private String saveXzAllPath;
    private String curVersionCode;
    private Thread downLoadThread; // 下载线程
    private VersionInfoBean versionInfoBean;
    private int curXzJd;// 当前进度
    private boolean qxXz = false;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    ToastShowUtil.showToastCenter(SetActivity.this, "清除成功");
                    try {
                        tvCache.setText(BusinessUtils.getTotalCacheSize(SetActivity.this));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case 1:
                    //安装包下载中
                    sbXzJd.setProgress(curXzJd);
                    tvXzApk.setText("下载中");
                    break;
                case 2:
                    //安装包下载完成
                    installApk();
                    llNewVersion.setVisibility(View.GONE);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getmImmersionBar().reset().statusBarColor(R.color.transparent).statusBarDarkFont(true, 0.2f).init();
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_set);
    }

    @Override
    protected void initData() {
        getApkCacheDir();
        String packName = this.getApplicationInfo().packageName;
        saveXzAllPath = apkXzPath + "ldmusic" + packName.substring(packName.lastIndexOf(".") + 1) + ".apk";
        tvVersion.setText("V" + BuildConfig.VERSION_NAME);
        try {
            tvCache.setText(BusinessUtils.getTotalCacheSize(SetActivity.this));
        } catch (Exception e) {
            e.printStackTrace();
        }
        initClick();
    }

    private void getNewVersion() {
        mPresenter.getNewVersion(true, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        VersionMainBean data = (VersionMainBean) object;
                        versionInfoBean = data.getData();
                        curVersionCode = data.getData().getOldversion();
                        if (BuildConfig.VERSION_NAME.equals(versionInfoBean.getNewversion())) {
                            llNewVersion.setVisibility(View.GONE);
                        } else {
                            llNewVersion.setVisibility(View.VISIBLE);
                            tvXzApk.setText("立即下载");
                            sbXzJd.setProgress(0);
                            tvVersionInfo.setText("有新版本：" + data.getData().getContent());
                        }
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(SetActivity.this, msg);
                        break;
                }
            }
        });
    }

    /**
     * 创建内部类，清除缓存
     */
    class clearCache implements Runnable {
        @Override
        public void run() {
            try {
                BusinessUtils.clearAllCache(SetActivity.this);
                Thread.sleep(1000);
                if (BusinessUtils.getTotalCacheSize(SetActivity.this).startsWith("0")) {
                    handler.sendEmptyMessage(0);
                }
            } catch (Exception e) {
                return;
            }
        }
    }

    private void tcLogin() {
        mPresenter.tcLogin(true, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        PreUtils.put(Constant.LOGIN_USER_INFO, "");
                        PreUtils.put(Constant.USER_KEY_TOKEN, "");
                        AppManager.getAppManager().finishAllActivity();
                        Intent intent = new Intent(SetActivity.this, LoginActivity.class);
                        startActivity(intent);
                        finish();
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(SetActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void zxZh() {
        mPresenter.zxZh(true, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        ToastShowUtil.showToastCenter(SetActivity.this, "账号已注销");
                        PreUtils.put(Constant.LOGIN_USER_INFO, "");
                        PreUtils.put(Constant.USER_KEY_TOKEN, "");
                        AppManager.getAppManager().finishAllActivity();
                        Intent intent = new Intent(SetActivity.this, LoginActivity.class);
                        startActivity(intent);
                        finish();
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(SetActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void rqCcQx() {
        final String[] permissionsGroup = new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE
                , Manifest.permission.READ_EXTERNAL_STORAGE};
        new RxPermissions(this)
                .request(permissionsGroup)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        Log.i("wxl", "下载安装包权限申请状态：" + aBoolean);
                        if (aBoolean) {
                            if (isAlreadLoadApk(SetActivity.this, curVersionCode, saveXzAllPath)) {
                                installApk(); // 安装文件
                            } else {
                                downLoadThread = new Thread(mdownApkRunnable);
                                downLoadThread.start();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private void rqAzApkQx() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
            intent.setData(Uri.parse("package:" + this.getPackageName()));
            startActivityForResult(intent, 1001);
        }
    }

    private Runnable mdownApkRunnable = new Runnable() {
        @Override
        public void run() {
            URL url;
            int length;
            InputStream ins;
            try {
                url = new URL(ApiUrl.API_BASE_URL + versionInfoBean.getDownloadurl());
                //url = new URL("https://wjyx.hnyywkj.com/apk/wjyx_jz_android-1.0.0-debug.apk");
                if (url.getProtocol().equals("https")) {
                    SSLContext sc = SSLContext.getInstance("SSL");
                    sc.init(null, new TrustManager[]{xtm}, new SecureRandom());
                    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                    HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier());
                    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                    conn.connect();
                    length = conn.getContentLength();
                    ins = conn.getInputStream();
                } else {
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    length = conn.getContentLength();
                    ins = conn.getInputStream();
                }
                File file = new File(apkXzPath);
                if (!file.exists()) {
                    file.mkdir();
                }
                String apkFile = saveXzAllPath;
                File ApkFile = new File(apkFile);
                FileOutputStream outStream = new FileOutputStream(ApkFile);
                int count = 0;
                byte buf[] = new byte[1024];
                do {
                    int numread = ins.read(buf);
                    count += numread;
                    curXzJd = (int) (((float) count / length) * 100) + 1;
                    Log.i("wxl", "安装包下载进度：" + curXzJd);
                    // 下载进度
                    handler.sendEmptyMessage(1);
                    if (numread <= 0) {
                        // 下载完成通知安装
                        handler.sendEmptyMessage(2);
                        break;
                    }
                    outStream.write(buf, 0, numread);
                } while (!qxXz);// 点击取消停止下载
                outStream.close();
                ins.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    /**
     * 安装APK文件
     */
    private void installApk() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (this.getPackageManager().canRequestPackageInstalls()) {
                startInstall(SetActivity.this, new File(saveXzAllPath));
            } else {
                rqAzApkQx();
            }
        } else {
            intent.setDataAndType(Uri.parse("file://" + saveXzAllPath), "application/vnd.android.package-archive");
        }
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK);//启动新的activity
        mContext.startActivity(intent);
    }

    private static void startInstall(Context context, File apkFile) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        Uri apkUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // Android 7.0+ 使用 FileProvider
            apkUri = FileProvider.getUriForFile(
                    context,
                    context.getPackageName() + ".fileprovider",
                    apkFile
            );
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            apkUri = Uri.fromFile(apkFile);
        }
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    private void getApkCacheDir() {
        //外部存储可用
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) || !Environment.isExternalStorageRemovable()) {
            apkXzPath = mContext.getExternalCacheDir() + "/download";
        } else {
            apkXzPath = mContext.getCacheDir() + "/download";
        }
    }

    /**
     * 判断是否已下载最新的apk安装包
     */
    private boolean isAlreadLoadApk(Context context, String serviceCode, String savefileApk) {
        //  savefileApk = savefileApk.replace("file://", "");
        PackageInfo info = context.getPackageManager().getPackageArchiveInfo(savefileApk, PackageManager.GET_ACTIVITIES);
        if (info == null) return false;
        return String.valueOf(info.versionCode).equals(serviceCode);
    }

    private X509TrustManager xtm = new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            X509Certificate[] x509Certificates = new X509Certificate[0];
            return x509Certificates;
        }
    };

    private class MyHostnameVerifier implements HostnameVerifier {

        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    private void initClick() {
        ivBack.setOnClickListener(view -> {
            qxXz = true;
            finish();
        });
        rlVersion.setOnClickListener(view -> {
            getNewVersion();
        });
        rlClearCache.setOnClickListener(view -> {
            new Thread(new clearCache()).start();
        });
        rlUserXy.setOnClickListener(view -> {
            Intent intent = new Intent(SetActivity.this, WebViewActivity.class);
            intent.putExtra("title", "用户协议");
            startActivity(intent);
        });
        rlYsXy.setOnClickListener(view -> {
            Intent intent = new Intent(SetActivity.this, WebViewActivity.class);
            intent.putExtra("title", "隐私协议");
            startActivity(intent);
        });
        rlAboutUs.setOnClickListener(view -> {
            Intent intent = new Intent(SetActivity.this, AboutUsActivity.class);
            startActivity(intent);
        });
        rlZxZh.setOnClickListener(view -> {
            zxZh();
        });
        tvCtLogin.setOnClickListener(view -> {
            tcLogin();
        });
        tvXzApk.setOnClickListener(view -> {
            if ("立即下载".equals(tvXzApk.getText().toString())) {
                rqCcQx();
            } else {
                ToastShowUtil.showToastCenter(SetActivity.this, "安装包下载中");
            }
        });
        sbXzJd.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return true;
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1001:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    if (getPackageManager().canRequestPackageInstalls()) {
                        // 权限已授予，继续安装流程
                        installApk();
                    } else {
                        // 处理权限拒绝
                        BusinessUtils.openAppSettings(SetActivity.this);
                    }
                }
                break;
        }
    }
}